package com.ruix.app.widget.chatrow;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.easeui.widget.EaseImageView;
import com.hyphenate.easeui.widget.chatrow.EaseChatRow;
import com.hyphenate.exceptions.HyphenateException;
import com.ruix.app.R;
import com.ruix.app.manager.UserManager;
import com.ruix.app.model.ChatAuther;
import com.ruix.app.model.Classes;
import com.ruix.app.util.RoleUtil;
import com.ruix.app.util.ViewUtil;

import org.json.JSONObject;

/**
 * Created by hadexs on 2017/5/29.
 */

public class ChatRowText extends EaseChatRow {

    private TextView contentView;
    private TextView autherNameView;
    private TextView autherTagView,setType,messageTypeTag;
    private EaseImageView userAvatar;
    private RelativeLayout typeContain;
    private TextView likeStatus;
//    private int maxTextWidth;

    public ChatRowText(Context context, EMMessage message, int position, BaseAdapter adapter) {
        super(context, message, position, adapter);
//        maxTextWidth =  (int) (ViewUtil.getWindowWidth(context) * 0.64);
    }

    @Override
    protected void onInflateView() {
        inflater.inflate(message.direct() == EMMessage.Direct.RECEIVE ? R.layout.ease_row_received_message :R.layout.ease_row_sent_message, this);
    }

    @Override
    protected void onFindViewById() {
        contentView = (TextView) findViewById(com.hyphenate.easeui.R.id.tv_chatcontent);
        autherNameView = (TextView) findViewById(com.hyphenate.easeui.R.id.tv_auther_name);
        autherTagView = (TextView) findViewById(com.hyphenate.easeui.R.id.tv_auther_tag);
        userAvatar = (EaseImageView) findViewById(com.hyphenate.easeui.R.id.iv_userhead);
        typeContain =  (RelativeLayout)findViewById(com.hyphenate.easeui.R.id.tv_self_type_contain);
        setType = (TextView) findViewById(com.hyphenate.easeui.R.id.tv_self_type);
        messageTypeTag = (TextView) findViewById(com.hyphenate.easeui.R.id.tv_message_type_bag);
        likeStatus = (TextView) findViewById(com.hyphenate.easeui.R.id.message_like);
//        contentView.setMaxWidth(maxTextWidth);
    }



    @Override
    public void onSetUpView() {
        try {
            String type =  message.getStringAttribute("type");
            if ("text".equals(type)){
                likeStatus.setVisibility(VISIBLE);
                typeContain.setVisibility(GONE);
                messageTypeTag.setVisibility(GONE);
            }else if ("target".equals(type)){ //ok
                likeStatus.setVisibility(GONE);
                setType.setText("明确目标");
                typeContain.setVisibility(VISIBLE);
                messageTypeTag.setVisibility(VISIBLE);
                messageTypeTag.setText("本期学习目标");
            }else if ("question".equals(type)){ // ok
                likeStatus.setVisibility(GONE); //点赞
                typeContain.setVisibility(GONE);
                messageTypeTag.setVisibility(VISIBLE);
                messageTypeTag.setText("问题");
            } else {
                likeStatus.setVisibility(GONE);
                typeContain.setVisibility(VISIBLE);
                typeContain.setVisibility(GONE);
                messageTypeTag.setVisibility(GONE);
            }
            handelUserInfo(type);
        } catch (Exception e){

        }

        likeStatus.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (itemClickListener != null){
                    itemClickListener.onLickClick(message);
                }
                didLikeClick();
            }
        });


        //// TODO: 2017/5/29  
        // 设置内容
        EMTextMessageBody txtBody = (EMTextMessageBody) message.getBody();
//        Spannable span = EaseSmileUtils.getSmiledText(context, txtBody.getMessage());
//        contentView.setText(span, TextView.BufferType.SPANNABLE);
        contentView.setText(txtBody.getMessage());
        handleTextMessage();

    }

    protected void handleTextMessage() {
        if (message.direct() == EMMessage.Direct.SEND) {
//            setMessageSendCallback();
            switch (message.status()) {
                case CREATE:
                    progressBar.setVisibility(View.GONE);
                    statusView.setVisibility(View.VISIBLE);
                    break;
                case SUCCESS:
                    progressBar.setVisibility(View.GONE);
                    statusView.setVisibility(View.GONE);
                    break;
                case FAIL:
                    progressBar.setVisibility(View.GONE);
                    statusView.setVisibility(View.VISIBLE);
                    break;
                case INPROGRESS:
                    progressBar.setVisibility(View.VISIBLE);
                    statusView.setVisibility(View.GONE);
                    break;
                default:
                    break;
            }
        }else{
//            if(!message.isAcked() && message.getChatType() == EMMessage.ChatType.Chat){
//                try {
//                    EMClient.getInstance().chatManager().ackMessageRead(message.getFrom(), message.getMsgId());
//                } catch (HyphenateException e) {
//                    e.printStackTrace();
//                }
//            }
        }
    }

    @Override
    protected void onUpdateView() {
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onBubbleClick() {
        // TODO Auto-generated method stub

    }

    protected void onBubbleLongClick(EMMessage message){

    }




    private void handelUserInfo(String messageType){
        try {
            JSONObject authorObj =  message.getJSONObjectAttribute("author");
            if (authorObj != null) {
                String authID = authorObj.optString("id", "");
                ChatAuther chatAuther =  UserManager.sharedInstance().getChatAuther(authID);
                if (chatAuther == null){
                    chatAuther = new ChatAuther();
                    String authName = authorObj.optString("name", "");
                    String roleid = authorObj.optString("role", "");
                    String roleVale = authorRoleValue(roleid);
                    String authAvatar = authorObj.optString("avatar", "");
                    chatAuther.setAuthID(authID);
                    chatAuther.setRoleid(roleid);
                    chatAuther.setAuthName(authName);
                    chatAuther.setRoleVale(roleVale);
                    chatAuther.setAuthAvatar(authAvatar);
                    UserManager.sharedInstance().addChatAuther(chatAuther);
                }
                if (!TextUtils.isEmpty(chatAuther.getAuthName())) {
                    autherNameView.setText(chatAuther.getAuthName());
                }
                if (!TextUtils.isEmpty(chatAuther.getAuthAvatar())) {
                    userAvatar.loadHeaderView(chatAuther.getAuthAvatar());
                }
                if (!TextUtils.isEmpty(chatAuther.getRoleVale())) {
                    autherTagView.setText(chatAuther.getRoleVale());
                    autherTagView.setVisibility(VISIBLE);
                } else {
                    autherTagView.setVisibility(GONE);
                }
                if (RoleUtil.isLikedUnusable(chatAuther.getRoleid())){
                    likeStatus.setVisibility(GONE);
                } else {
                    //点赞的逻辑 普通消息有点赞逻辑
                    if (!"target".equals(messageType) && !"question".equals(messageType)) { //ok
                        boolean hasLike = message.getIntAttribute("has_like", 0) == 1;
                        int likeCnt = message.getIntAttribute("like_cnt", 0);
                        if (likeCnt > 0) {
                            likeStatus.setText(String.format("赞同%d", likeCnt));
                        } else {
                            likeStatus.setText("赞同");
                        }
                        if (hasLike && likeCnt > 0) {
                            likeStatus.setBackgroundResource(com.hyphenate.easeui.R.drawable.ease_like_action_bg);
                        } else {
                            likeStatus.setBackgroundResource(com.hyphenate.easeui.R.drawable.ease_like_normal_bg);
                        }
                        likeStatus.setVisibility(VISIBLE);
                    } else {
                        likeStatus.setVisibility(GONE);
                    }
                }
            }


        } catch (Exception e){

        }

    }


    private void didLikeClick(){
        boolean  hasLike =  message.getIntAttribute("has_like",0) == 1;
        int  likeCnt =  message.getIntAttribute("like_cnt",0);
        if (hasLike){
            likeCnt--;
            likeStatus.setBackgroundResource(com.hyphenate.easeui.R.drawable.ease_like_normal_bg);
            message.setAttribute("has_like",0);
        } else {
            likeCnt++;
            likeStatus.setBackgroundResource(com.hyphenate.easeui.R.drawable.ease_like_action_bg);
            message.setAttribute("has_like",1);
        }

        if (likeCnt > 0) {
            likeStatus.setText(String.format("赞同%d", likeCnt));
        } else {
            likeStatus.setText("赞同");
        }
        message.setAttribute("like_cnt",likeCnt);
    }

    public String authorRoleValue(String roleID){
        if (!TextUtils.isEmpty(roleID)) {
            if ("1".equals(roleID)){
                return "导师";
            } else if ("5".equals(roleID)){
                return "小助手";
            } else if ("6".equals(roleID)){
                return "嘉宾";
            } else if ("8".equals(roleID)){
                Classes currentClass =  UserManager.sharedInstance().getCurrentClass();
                if (currentClass != null &&  currentClass.isTeacherFriendCircle()){
                    return "导师";
                }
                return "班主任"; //
            } else if ("9".equals(roleID)){
                return "班委";
            } else if ("10".equals(roleID)){
                return "班长";
            }
        }
        return null;
    }

}
